package org.jeecg.modules.demo.ch.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.ch.common.CommonMst;
import org.jeecg.modules.demo.ch.entity.ChSysProblemAllocation;
import org.jeecg.modules.demo.ch.exception.Assert;
import org.jeecg.modules.demo.ch.exception.CustomException;
import org.jeecg.modules.demo.ch.service.IChSysProblemAllocationService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 系统问题分配
 * @Author: jeecg-boot
 * @Date: 2022-11-15
 * @Version: V1.0
 */
@Api(tags = "系统问题分配")
@RestController
@RequestMapping("/ch/chSysProblemAllocation")
@Slf4j
public class ChSysProblemAllocationController extends JeecgController<ChSysProblemAllocation, IChSysProblemAllocationService> {
    @Autowired
    private IChSysProblemAllocationService chSysProblemAllocationService;

    @Autowired
    private SysBaseApiImpl sysBaseApi;

    @Autowired
    private ISysUserService sysUserService;

    @Lazy
    @Resource
    private CommonAPI commonApi;

    /**
     * 查询字典列表（系统名称、问题类型）
     *
     * @return
     */
    @AutoLog(value = "系统问题分配-查询字典列表（系统名称、问题类型）")
    @ApiOperation(value = "系统问题分配-查询字典列表（系统名称、问题类型）", notes = "系统问题分配-查询字典列表（系统名称、问题类型）")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_sys_problem_allocation:add")
    @GetMapping(value = "/queryDistListByCode")
    public Result<Map<String, List<DictModel>>> queryDistListByCode() {
        List<String> dictCodeList = new ArrayList<>();
        dictCodeList.add(CommonMst.DEMAND_FEEDBACK_SYSTEM.SYSTEM_CODE);
        dictCodeList.add(CommonMst.DEMAND_FEEDBACK_SYSTEM.PROBLEM_TYPE);
        Map<String, List<DictModel>> manyDictItems = sysBaseApi.getManyDictItems(dictCodeList);
        log.info("返回的数据manyDictItems:{}", manyDictItems);
        return Result.OK(manyDictItems);
    }

    /**
     * 查询IT部的所有员工信息
     *
     * @param
     * @return
     */
    @AutoLog(value = "软件运维计划表-查询IT部的所有员工信息")
    @ApiOperation(value = "软件运维计划表-查询IT部的所有员工信息", notes = "软件运维计划表-查询IT部的所有员工信息")
    @GetMapping(value = "/queryLoginUsersByDeptId")
    public Result<List<LoginUser>> queryLoginUsersByDeptId() {
        List<LoginUser> userByDeptId = commonApi.getUserByDeptId(CommonMst.SOFTWARE.IT_DEPT_ID);
//		sysBaseApi.sendSysAnnouncement();
        return Result.ok(userByDeptId);
    }

    /**
     * 根据系统名称和问题类型查询是否已分配
     *
     * @param chSysProblemAllocation
     * @param flag  (add新增,edit编辑)
     * @return
     */
    public Boolean queryListBySysNameAndProblemType(ChSysProblemAllocation chSysProblemAllocation,String flag) {
        LambdaQueryWrapper<ChSysProblemAllocation> sysProblemAllocationLambdaQueryWrapper = null;
        if (flag.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.ADD)) {
            sysProblemAllocationLambdaQueryWrapper = new QueryWrapper<ChSysProblemAllocation>().lambda()
                    .eq(ChSysProblemAllocation::getSystemName, chSysProblemAllocation.getSystemName())
                    .eq(ChSysProblemAllocation::getProblemType, chSysProblemAllocation.getProblemType());
        }else if (flag.equals(CommonMst.DEMAND_FEEDBACK_SYSTEM.EDIT)){
            //排除本条记录进行查询.
            sysProblemAllocationLambdaQueryWrapper = new QueryWrapper<ChSysProblemAllocation>().lambda()
                    .eq(ChSysProblemAllocation::getSystemName, chSysProblemAllocation.getSystemName())
                    .eq(ChSysProblemAllocation::getProblemType, chSysProblemAllocation.getProblemType())
                    .ne(ChSysProblemAllocation::getId,chSysProblemAllocation.getId());
        }
        List<ChSysProblemAllocation> chSysProblemAllocationList = chSysProblemAllocationService.list(sysProblemAllocationLambdaQueryWrapper);
        return CollectionUtils.isEmpty(chSysProblemAllocationList);
    }

    /**
     * 系统问题分配-添加
     *
     * @param chSysProblemAllocation
     * @return
     */
    @AutoLog(value = "系统问题分配-添加")
    @ApiOperation(value = "系统问题分配-添加", notes = "系统问题分配-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_sys_problem_allocation:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody ChSysProblemAllocation chSysProblemAllocation) {
        try {
            log.info("传过来的参数chSysProblemAllocation:{}", chSysProblemAllocation);
            //非空数据校验
            Assert.validateEntity(chSysProblemAllocation);
            //校验是否重复
            Boolean aBoolean = queryListBySysNameAndProblemType(chSysProblemAllocation,CommonMst.DEMAND_FEEDBACK_SYSTEM.ADD);
            if (!aBoolean){
                return Result.error("该系统名字和问题类型已分配！请核查后再添加!");
            }
            String allocator = getAllocator(chSysProblemAllocation);
            chSysProblemAllocation.setAllocator(allocator);
            chSysProblemAllocationService.save(chSysProblemAllocation);
            return Result.OK("添加成功！");
        } catch (CustomException e) {
            e.printStackTrace();
            log.error("数据校验异常", e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 分页列表查询
     *
     * @param chSysProblemAllocation
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "系统问题分配-分页列表查询")
    @ApiOperation(value = "系统问题分配-分页列表查询", notes = "系统问题分配-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ChSysProblemAllocation>> queryPageList(ChSysProblemAllocation chSysProblemAllocation,
                                                               @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                               HttpServletRequest req) {
        log.info("传过来的参数chSysProblemAllocation:{}", chSysProblemAllocation);
//		QueryWrapper<ChSysProblemAllocation> queryWrapper = QueryGenerator.initQueryWrapper(chSysProblemAllocation, req.getParameterMap());
        String allocator = chSysProblemAllocation.getAllocator();
        String problemType = chSysProblemAllocation.getProblemType();//问题类型
        String systemName = chSysProblemAllocation.getSystemName();//系统名称
        LambdaQueryWrapper<ChSysProblemAllocation> allocationLambdaQueryWrapper = new QueryWrapper<ChSysProblemAllocation>().lambda()
                .like(StringUtils.hasLength(allocator), ChSysProblemAllocation::getAllocator, allocator)
                .like(StringUtils.hasLength(problemType), ChSysProblemAllocation::getProblemType, problemType)
                .like(StringUtils.hasLength(systemName), ChSysProblemAllocation::getSystemName, systemName)
                .orderByAsc(ChSysProblemAllocation::getSystemName)
                .orderByAsc(ChSysProblemAllocation::getProblemType)
                .orderByAsc(ChSysProblemAllocation::getAllocator);
        Page<ChSysProblemAllocation> page = new Page<>(pageNo, pageSize);
        IPage<ChSysProblemAllocation> pageList = chSysProblemAllocationService.page(page, allocationLambdaQueryWrapper);
        List<ChSysProblemAllocation> records = pageList.getRecords();
        //存放真实姓名 用于显示
        records.stream().forEach(
                p -> {
                    String allocator1 = p.getAllocator();
                    ArrayList<String> realnameList = new ArrayList<>();//存放真实姓名 用于显示
                    ArrayList<String> userNameList = new ArrayList<>();//存放userNameList 用于编辑回写
                    if (StringUtils.hasLength(allocator1)) {
                        if (allocator1.contains(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA)) {
                            String[] split = allocator1.split(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA);
                            for (String username : split) {
                                LoginUser loginUser = sysBaseApi.getUserByName(username);
                                realnameList.add(loginUser.getRealname());
                                userNameList.add(loginUser.getUsername());
                            }
                        } else {
                            LoginUser loginUser = sysBaseApi.getUserByName(allocator1);
                            realnameList.add(loginUser.getRealname());
                            userNameList.add(loginUser.getUsername());
                        }
                        p.setAllocator(String.join(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA, realnameList));
                        p.setAllocatorIds(String.join(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA, userNameList));
                        //集合转数组
                        String[] allocatorList = new String[realnameList.size()];
                        realnameList.toArray(allocatorList);
                        p.setAllocatorList(allocatorList);
                    }
                }
        );
        return Result.OK(pageList);
    }


    /**
     * 编辑
     *
     * @param chSysProblemAllocation
     * @return
     */
    @AutoLog(value = "系统问题分配-编辑")
    @ApiOperation(value = "系统问题分配-编辑", notes = "系统问题分配-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_sys_problem_allocation:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody ChSysProblemAllocation chSysProblemAllocation) {
        try {
            Assert.validateEntity(chSysProblemAllocation);
            //非空数据校验
            Assert.validateEntity(chSysProblemAllocation);
            //校验是否重复
            Boolean aBoolean = queryListBySysNameAndProblemType(chSysProblemAllocation,CommonMst.DEMAND_FEEDBACK_SYSTEM.EDIT);
            if (!aBoolean){
               return Result.error("该系统名字和问题类型已分配！请核查后再添加!");
            }
            String allocator = getAllocator(chSysProblemAllocation);
            chSysProblemAllocation.setAllocator(allocator);
            chSysProblemAllocationService.updateById(chSysProblemAllocation);
            return Result.OK("编辑成功!");
        } catch (CustomException e) {
            e.printStackTrace();
            log.error("数据校验异常!", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "系统问题分配-通过id删除")
    @ApiOperation(value = "系统问题分配-通过id删除", notes = "系统问题分配-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_sys_problem_allocation:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        chSysProblemAllocationService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "系统问题分配-批量删除")
    @ApiOperation(value = "系统问题分配-批量删除", notes = "系统问题分配-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:ch_sys_problem_allocation:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.chSysProblemAllocationService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "系统问题分配-通过id查询")
    @ApiOperation(value = "系统问题分配-通过id查询", notes = "系统问题分配-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<ChSysProblemAllocation> queryById(@RequestParam(name = "id", required = true) String id) {
        ChSysProblemAllocation chSysProblemAllocation = chSysProblemAllocationService.getById(id);
        if (chSysProblemAllocation == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(chSysProblemAllocation);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param chSysProblemAllocation
     */
    //@RequiresPermissions("org.jeecg.modules.demo:ch_sys_problem_allocation:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ChSysProblemAllocation chSysProblemAllocation) {
        return super.exportXls(request, chSysProblemAllocation, ChSysProblemAllocation.class, "系统问题分配");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("ch_sys_problem_allocation:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ChSysProblemAllocation.class);
    }

    /**
     * 将分配人列表转String
     *
     * @param chSysProblemAllocation
     * @return
     */
    public String getAllocator(ChSysProblemAllocation chSysProblemAllocation) {
        String[] allocatorList = chSysProblemAllocation.getAllocatorList();
        String allocator = "";
        if (allocatorList != null && allocatorList.length > 0) {
            //将realname转换为username
            List<String> usernameList = Arrays.stream(allocatorList).map(p -> {
                LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new QueryWrapper<SysUser>().lambda()
                        .eq(SysUser::getRealname, p);
                List<SysUser> list = sysUserService.list(userLambdaQueryWrapper);
                if (!CollectionUtils.isEmpty(list)) {
                    String username = list.get(0).getUsername();
                    return username;
                } else {
                    return "";
                }
            }).collect(Collectors.toList());
            allocator = String.join(CommonMst.DEMAND_FEEDBACK_SYSTEM.COMMA, usernameList);//分配人
        }
        return allocator;
    }

}
